package com.ouheng.common.utils;

import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class WxPushThreadUtils{
	
	

	
    private static Logger logger = Logger.getLogger(WxPushThreadUtils.class);
	
	
	 public static void sendSMS(String access_token,List<String> mobileList, String content,Map<String,Object> m) throws Exception {
	        try {
	            logger.info("send message start...");
	            long startTime = System.currentTimeMillis();
	            BlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>(20000);
	            ThreadPoolExecutor executors = new ThreadPoolExecutor(5, 10, 60000, TimeUnit.SECONDS, queue);

	            // 要推送的用户总数
	            int count = mobileList.size();
	            logger.info("message all count=" + count);
	            // 初始每个线程处理的用户数量
	            final int eveLength = 5;
	            // 计算处理所有用户需要的线程数量
	            int eveBlocks = count / eveLength + (count % eveLength != 0 ? 1 : 0);
	            logger.info("need thread's count=" + eveBlocks);
	            // 线程计数器
	            CountDownLatch doneSignal = new CountDownLatch(eveBlocks);

	            // 开启线程处理
	            int doneCount = 0;
	            for (int page = 0; page < eveBlocks; page++) { /* blocks太大可以再细分重新调度 */
	                content = content + ",线程" + (page + 1);
	                WxPushThreadImpl ms = new WxPushThreadImpl(access_token,mobileList, content, page, eveLength, doneSignal,m);
	                executors.execute(ms);
	                // logger.info("start thread =>{}",page+1);
	                doneCount++;
	            }
	            doneSignal.await();// 等待所有计数器线程执行完
	            long endTime = System.currentTimeMillis();
	            logger.info("send message all thread ends!time(s)=" + (startTime - endTime) / 1000);
	            logger.info("all thread count=" + doneCount);
	        } catch (Exception e) {
	            logger.error("send message error=>{}", e);
	        }
	    }
	

	 
	 

	    
	    
	    

	    
}
